import bodyParser from 'body-parser';
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import helmet from 'helmet';
import logger from './logger.js';
import busboy from 'connect-busboy';
module.exports = app => {
	const userManager = app.service.userManager;
	const config = app.libs.config;
	app.set('json spaces', 4);
	app.use(morgan('common', {
		stream: {
		write: (message) => {
			logger.info(message);
		},
		},
	}));
	app.use(bodyParser.json());
	// app.use(bodyParser.urlencoded());
	app.use(async(req, res, next) => {
		if(!!config.auth && config.auth[req.url] == false){
			console.log("without auth")
            next();
        }else{
			try{
				let uid = req.header("uid")
				// console.log("uid is ",uid);
				if(!uid){
					next(new Error("Bad Authorized"));
				}
				let user = await userManager.getUserById(uid)
				if(!user && !user.id ){
					next(new Error("403","Bad Authorized"));
				}
				req.user = user; 
				next();
			} catch(e){
				console.log(e)
				next(new Error("403","Bad Authorized"));
				return;
			}
		}
		
	});
	/*
	app.use(helmet());
	app.use(cors({
		origin: ['http://localhost:3001'],
		methods: ['GET', 'POST', 'PUT', 'DELETE'],
		allowedHeaders: ['Content-Type', 'Authorization'],
	}));
	app.use(app.auth.initialize());
	app.use((req, res, next) => {
		delete req.body.id;
		next();
	});
	app.use(express.static('public'));
	*/
};